// .........................................................................
// Title: factset_dcs.do
//
// Imports and cleans data from Factset Debt Capital Structure (DCS) dataset
// .........................................................................

* build dcs data
use "$raw/factset/dcs_details.dta", clear
keep report_date instrument_id os_amount
gcollapse (firstnm) os_amount, by(instrument_id report_date)
drop if missing(instrument_id) | missing(report_date)
drop if missing(os_amount)
mmerge instrument_id using "$raw/factset/sym_cusip.dta", unmatched(m) umatch(fsym_id)
drop if missing(cusip)
drop _merge
gcollapse (firstnm) os_amount, by(cusip report_date)
save "$tmp/dcs_os_amounts", replace

* quarterly frequency
use "$tmp/dcs_os_amounts", clear
gen date = date(report_date, "YMD")
format %td date
gen date_q = qofd(date)
format %tq date_q
drop date report_date
gcollapse (firstnm) os_amount, by(cusip date_q)
save "$tmp/dcs_os_amounts_q", replace

* yearly frequency
use "$tmp/dcs_os_amounts_q", clear
gen year = year(dofq(date_q))
gsort cusip year -date_q
by cusip year: keep if _n == 1
drop date_q
order cusip year
save "$tmp/dcs_os_amounts_y", replace
